package cn.shengchao.examstarvideo.util;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.vod20170321.AsyncClient;
import com.aliyun.sdk.service.vod20170321.models.BatchGetMediaInfosRequest;
import com.aliyun.sdk.service.vod20170321.models.BatchGetMediaInfosResponse;
import com.aliyun.sdk.service.vod20170321.models.BatchGetMediaInfosResponseBody;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class AliVideoUploadUtil {

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    public CreateUploadVideoResponse getVideoPlayAuth(String title, String fileName) throws ClientException {
        AssumeRoleResponse response = getAssumeRoleResponse();
        return createUploadVideo(title, fileName, response.getCredentials().getAccessKeyId(), response.getCredentials().getAccessKeySecret(), response.getCredentials().getSecurityToken());
    }

    private static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleSessionName, String policy) throws ClientException {
        IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setSysEndpoint("sts.aliyuncs.com");
        request.setSysMethod(MethodType.POST);
        request.setRoleArn("acs:ram::1274681370210884:role/vodrole");
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);
        return client.getAcsResponse(request);
    }

    private static CreateUploadVideoResponse createUploadVideo(String title, String fileName, String accessKeyId, String accessKeySecret, String token) throws ClientException {
        String regionId = "cn-shenzhen";
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setSecurityToken(token);
        request.setTitle(title);
        request.setFileName(fileName);
        return client.getAcsResponse(request);
    }

    public RefreshUploadVideoResponse refreshVideoPlayAuth(String videoId) throws ClientException {
        AssumeRoleResponse response = getAssumeRoleResponse();
        return refreshUploadVideo(videoId,  response.getCredentials().getAccessKeyId(), response.getCredentials().getAccessKeySecret(), response.getCredentials().getSecurityToken());
    }
    private static RefreshUploadVideoResponse refreshUploadVideo(String videoId, String accessKeyId, String accessKeySecret, String token) throws ClientException {
        String regionId = "cn-shenzhen";
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        request.setVideoId(videoId);
        request.setSecurityToken(token);
        return client.getAcsResponse(request);
    }

    public BatchGetMediaInfosResponseBody.MediaInfos getVideoInfo(String videoId) throws ExecutionException, InterruptedException, ClientException {
        AssumeRoleResponse assumeRole = getAssumeRoleResponse();
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(assumeRole.getCredentials().getAccessKeyId())
                .accessKeySecret(assumeRole.getCredentials().getAccessKeySecret())
                .securityToken(assumeRole.getCredentials().getSecurityToken())
                .build());
        try (AsyncClient client = AsyncClient.builder()
                .region("cn-shenzhen") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("vod.cn-shenzhen.aliyuncs.com")
                ).build()) {
            BatchGetMediaInfosRequest batchGetMediaInfosRequest = BatchGetMediaInfosRequest.builder()
                    .mediaIds(videoId)
                    .build();
            CompletableFuture<BatchGetMediaInfosResponse> response = client.batchGetMediaInfos(batchGetMediaInfosRequest);
            BatchGetMediaInfosResponse batchGetMediaInfosResponse = response.get();
            List<BatchGetMediaInfosResponseBody.MediaInfos> mediaInfos = batchGetMediaInfosResponse.getBody().getMediaInfos();
            return mediaInfos.get(0);
        }
    }

    private AssumeRoleResponse getAssumeRoleResponse() throws ClientException {
        String roleSessionName = "session-name";
        String policy = """
                {
                  "Version": "1",
                  "Statement": [
                    {
                      "Action": "vod:*",
                      "Resource": "*",
                      "Effect": "Allow"
                    }
                  ]
                }""";
        return assumeRole(accessKeyId, accessKeySecret, roleSessionName, policy);
    }
}
